package wiki.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import wiki.generic.io.User;
import wiki.setup.Setup;
/**
 * 
 * @author <p><strong>JwTeam</strong></p> 
 * Responsabile della fase di login
 */
public class LoginServlet extends HttpServlet  {

	
	private static final String TO_REGISTER = "toregister";
	private static final String STUD_ID="stud";
	private static final String STUD_PSW="stud";
	
	
	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {	
	
		HttpSession ses=req.getSession(false);
		if(ses==null) {
				if(req.getParameterMap().containsKey("username") && req.getParameterMap().containsKey("password")){
				String user=req.getParameter("username");
				String pass=req.getParameter("password");
				String rights=getAuthenticationRights(user, pass);
				if(rights!=null) {
					if(rights.compareTo(TO_REGISTER)==0){
						resp.sendRedirect("./html/registrazione/registrazione.html"); 
					} 
					else{
					ses=req.getSession(true);
					boolean aut;
					if(rights.equals("docente")){
						aut=true;
					} else {
						aut=false;
					}
					ses.setAttribute("rights", aut);
					ses.setAttribute("id", user);
					String corso=Setup.getSetup().getMediator().getLoginService().getUser(user).getCorso();
					ses.setAttribute("corso", corso);
					resp.sendRedirect("./view?page=index");
					}
					}else {
						resp.sendRedirect("./html/LOGIN/login.html"); 
					}
				} else {
					resp.sendRedirect("./html/errorpages/nopermessi.html");
				} 
				
	    } else {
	    	ses.invalidate();
	    	resp.sendRedirect("./html/LOGIN/login.html");
	    }
	
	}

	private String getAuthenticationRights(String user, String pass){

		if(user.equals(STUD_ID) && pass.equals(STUD_PSW)) {
			return TO_REGISTER;
		}
		
		User us=Setup.getSetup().getMediator().getLoginService().getUser(user);		
		if(us!=null && us.getPassword().equals(pass)){
				
			if(us.isDocente()){
				return "docente";
			} else {
				return "studente";
			}
		}		
		return null;
	}

	

	
}
